package com.bnz.service.impl;

import com.bnz.entity.Classes;
import com.bnz.entity.Student;
import com.bnz.entity.vo.StudentVo;
import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.mybatis.mapper.example.ExampleWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service // 注入到spring容器中
public class StudentServiceImpl implements StudentService {

    // 引入mapper
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public List<Student> findAll() {
        List<Student> list = studentMapper.selectByExample(null);// 没有条件就是查询全部
        return list;
    }

    // 2、条件查询带分页
    @Override
    public PageResult<Student> search(int page, int pagesize, StudentVo studentVo) {
        // 2.1、开始分页
        PageHelper.startPage(page,pagesize);
        // 2.2、条件查询(定义条件构造器)
        ExampleWrapper<Student, Integer> wrapper = studentMapper.wrapper();
        // 2.3、定义条件
        wrapper.like(Student::getAddr,"%"+studentVo.getAddr()+"%")
                .like(Student::getSname,"%"+studentVo.getSname()+"%");
        // 2.4、判断输入的班级id是否为0
        if (studentVo.getCid() != 0){
            wrapper.eq(Student::getCid,studentVo.getCid());
        }
        // 2.5、用条件构造器对象创建一个list集合
        List<Student> list = wrapper.list();
        // 2.6、设置班级
        for (Student student : list) {
            // 获取班级编号
            Optional<Classes> classes = classesMapper.selectByPrimaryKey(student.getCid());
            Classes classes1 = classes.get();
            // 设置班级名称
            student.setCname(classes1.getCname());
        }
        // 2.7、将其包装为PageInfo
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        // 2.8、返回分页对象
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }
}
